package com.example.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.project.common.Result;
import com.example.project.entity.*;
import com.example.project.mapper.*;
import com.example.project.request.*;
import com.example.project.response.*;
import com.example.project.service.ProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductMapper productMapper;

    @Resource
    private ProductImageMapper productImageMapper;

    @Resource
    private ProductSpecMapper productSpecMapper;

    @Resource
    private ProductReviewMapper productReviewMapper;

    @Resource
    private ProductFavoriteMapper productFavoriteMapper;

    @Resource
    private ShopMapper shopMapper;

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ProductStockLogMapper stockLogMapper;

    @Resource
    private ProductStatsMapper statsMapper;

    @Resource
    private ProductRecommendationMapper recommendationMapper;

    @Override
    @Transactional
    public Result<?> deleteProduct(Long productId, Long userId) {
        // 检查商品是否存在且属于该商家
        Product product = checkProductOwnership(productId, userId);
        if (product == null) {
            return Result.error("商品不存在或无权限操作");
        }

        // 删除商品图片关联
        productImageMapper.delete(
            new LambdaQueryWrapper<ProductImage>()
                .eq(ProductImage::getProductId, productId)
        );

        // 删除商品规格
        productSpecMapper.delete(
            new LambdaQueryWrapper<ProductSpec>()
                .eq(ProductSpec::getProductId, productId)
        );

        // 删除商品评价
        productReviewMapper.delete(
            new LambdaQueryWrapper<ProductReview>()
                .eq(ProductReview::getProductId, productId)
        );

        // 删除商品收藏
        productFavoriteMapper.delete(
            new LambdaQueryWrapper<ProductFavorite>()
                .eq(ProductFavorite::getProductId, productId)
        );

        // 删除商品
        productMapper.deleteById(productId);

        return Result.success();
    }

    @Override
    @Transactional
    public Result<?> updateProductStatus(Long productId, Integer status, Long userId) {
        // 检查商品是否存在且属于该商家
        Product product = checkProductOwnership(productId, userId);
        if (product == null) {
            return Result.error("商品不存在或无权限操作");
        }

        // 更新商品状态
        product.setStatus(status);
        productMapper.updateById(product);

        return Result.success();
    }

    @Override
    public Result<ProductResponse> getProductDetail(Long productId) {
        // 获取商品基本信息
        Product product = productMapper.selectById(productId);
        if (product == null) {
            return Result.error("商品不存在");
        }

        // 转换为响应对象
        ProductResponse response = convertToProductResponse(product);

        // 获取商品评价
        Page<ProductReview> reviewPage = new Page<>(1, 10);
        Page<ProductReview> reviews = productReviewMapper.selectPage(reviewPage,
            new LambdaQueryWrapper<ProductReview>()
                .eq(ProductReview::getProductId, productId)
                .eq(ProductReview::getStatus, 1)
                .orderByDesc(ProductReview::getCreatedAt)
        );
        response.setReviews(convertToReviewResponse(reviews.getRecords()));

        return Result.success(response);
    }

    @Override
    public Result<Page<ProductResponse>> searchProducts(ProductSearchRequest request) {
        // 构建查询条件
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<Product>()
            .eq(Product::getStatus, 1)  // 只查询上架商品
            .like(request.getKeyword() != null, Product::getName, request.getKeyword())
            .eq(request.getCategoryId() != null, Product::getCategoryId, request.getCategoryId())
            .ge(request.getMinPrice() != null, Product::getPrice, request.getMinPrice())
            .le(request.getMaxPrice() != null, Product::getPrice, request.getMaxPrice());

        // 添加排序
        if ("price".equals(request.getSortField())) {
            wrapper.orderBy(true, "asc".equals(request.getSortOrder()), Product::getPrice);
        } else {
            wrapper.orderByDesc(Product::getCreatedAt);
        }

        // 执行分页查询
        Page<Product> page = new Page<>(request.getPageNum(), request.getPageSize());
        Page<Product> productPage = productMapper.selectPage(page, wrapper);

        // 转换为响应对象
        return Result.success(convertToProductResponsePage(productPage));
    }

    @Override
    @Transactional
    public Result<?> createReview(ProductReviewRequest request, Long userId) {
        // 检查商品是否存在
        Product product = productMapper.selectById(request.getProductId());
        if (product == null) {
            return Result.error("商品不存在");
        }

        // 创建评价
        ProductReview review = new ProductReview();
        BeanUtils.copyProperties(request, review);
        review.setUserId(userId);
        review.setStatus(1);
        productReviewMapper.insert(review);

        return Result.success();
    }

    @Override
    @Transactional
    public Result<?> replyReview(Long reviewId, String reply, Long userId) {
        // 获取评价
        ProductReview review = productReviewMapper.selectById(reviewId);
        if (review == null) {
            return Result.error("评价不存在");
        }

        // 检查商品是否属于该商家
        Product product = checkProductOwnership(review.getProductId(), userId);
        if (product == null) {
            return Result.error("无权限回复");
        }

        // 更新回复
        review.setReply(reply);
        review.setReplyTime(LocalDateTime.now());
        productReviewMapper.updateById(review);

        return Result.success();
    }

    @Override
    public Result<Page<ProductReviewResponse>> getProductReviews(Long productId, Integer pageNum, Integer pageSize) {
        // 分页查询评价
        Page<ProductReview> page = new Page<>(pageNum, pageSize);
        Page<ProductReview> reviewPage = productReviewMapper.selectPage(page,
            new LambdaQueryWrapper<ProductReview>()
                .eq(ProductReview::getProductId, productId)
                .eq(ProductReview::getStatus, 1)
                .orderByDesc(ProductReview::getCreatedAt)
        );

        // 转换为响应对象
        Page<ProductReviewResponse> responsePage = new Page<>();
        BeanUtils.copyProperties(reviewPage, responsePage, "records");
        responsePage.setRecords(convertToReviewResponse(reviewPage.getRecords()));

        return Result.success(responsePage);
    }

    @Override
    @Transactional
    public Result<?> favoriteProduct(Long productId, Long userId) {
        // 检查商品是否存在
        Product product = productMapper.selectById(productId);
        if (product == null) {
            return Result.error("商品不存在");
        }

        // 检查是否已收藏
        ProductFavorite exist = productFavoriteMapper.selectOne(
            new LambdaQueryWrapper<ProductFavorite>()
                .eq(ProductFavorite::getProductId, productId)
                .eq(ProductFavorite::getUserId, userId)
        );
        if (exist != null) {
            return Result.error("已收藏该商品");
        }

        // 添加收藏
        ProductFavorite favorite = new ProductFavorite();
        favorite.setProductId(productId);
        favorite.setUserId(userId);
        productFavoriteMapper.insert(favorite);

        return Result.success();
    }

    @Override
    @Transactional
    public Result<?> unfavoriteProduct(Long productId, Long userId) {
        productFavoriteMapper.delete(
            new LambdaQueryWrapper<ProductFavorite>()
                .eq(ProductFavorite::getProductId, productId)
                .eq(ProductFavorite::getUserId, userId)
        );
        return Result.success();
    }

    @Override
    public Result<Boolean> checkFavorite(Long productId, Long userId) {
        ProductFavorite favorite = productFavoriteMapper.selectOne(
            new LambdaQueryWrapper<ProductFavorite>()
                .eq(ProductFavorite::getProductId, productId)
                .eq(ProductFavorite::getUserId, userId)
        );
        return Result.success(favorite != null);
    }

    @Override
    public Result<Page<ProductResponse>> getFavorites(Long userId, Integer pageNum, Integer pageSize) {
        // 分页查询收藏的商品
        Page<ProductFavorite> page = new Page<>(pageNum, pageSize);
        Page<ProductFavorite> favoritePage = productFavoriteMapper.selectPage(page,
            new LambdaQueryWrapper<ProductFavorite>()
                .eq(ProductFavorite::getUserId, userId)
                .orderByDesc(ProductFavorite::getCreatedAt)
        );

        // 获取商品详情
        List<Product> products = productMapper.selectBatchIds(
            favoritePage.getRecords().stream()
                .map(ProductFavorite::getProductId)
                .collect(Collectors.toList())
        );

        // 转换为响应对象
        Page<ProductResponse> responsePage = new Page<>();
        BeanUtils.copyProperties(favoritePage, responsePage, "records");
        responsePage.setRecords(convertToProductResponse(products));

        return Result.success(responsePage);
    }

    @Override
    @Transactional
    public Result<?> createProduct(ProductRequest request, Long userId) {
        // 获取商家店铺
        Shop shop = getShopByUserId(userId);
        if (shop == null) {
            return Result.error("请先创建店铺");
        }

        // 创建商品
        Product product = new Product();
        BeanUtils.copyProperties(request, product);
        product.setShopId(shop.getId());
        product.setStatus(1);  // 默认上架
        product.setSales(0);   // 初始销量为0
        productMapper.insert(product);

        // 保存商品图片
        if (request.getImageIds() != null && !request.getImageIds().isEmpty()) {
            saveProductImages(product.getId(), request.getImageIds());
            // 设置主图
            product.setMainImage(request.getImageIds().get(0).toString());
            productMapper.updateById(product);
        }

        // 保存商品规格
        if (request.getSpecs() != null && !request.getSpecs().isEmpty()) {
            saveProductSpecs(product.getId(), request.getSpecs());
        }

        return Result.success();
    }

    @Override
    @Transactional
    public Result<?> updateProduct(Long productId, ProductRequest request, Long userId) {
        // 检查商品是否存在且属于该商家
        Product product = checkProductOwnership(productId, userId);
        if (product == null) {
            return Result.error("商品不存在或无权限操作");
        }

        // 更新商品基本信息
        BeanUtils.copyProperties(request, product);
        
        // 更新商品图片
        if (request.getImageIds() != null && !request.getImageIds().isEmpty()) {
            // 删除原有图片关联
            productImageMapper.delete(
                new LambdaQueryWrapper<ProductImage>()
                    .eq(ProductImage::getProductId, productId)
            );
            // 保存新图片
            saveProductImages(productId, request.getImageIds());
            // 更新主图
            product.setMainImage(request.getImageIds().get(0).toString());
        }

        // 更新商品规格
        if (request.getSpecs() != null) {
            // 删除原有规格
            productSpecMapper.delete(
                new LambdaQueryWrapper<ProductSpec>()
                    .eq(ProductSpec::getProductId, productId)
            );
            // 保存新规格
            saveProductSpecs(productId, request.getSpecs());
        }

        // 更新商品信息
        productMapper.updateById(product);

        return Result.success();
    }

    @Override
    public Result<Page<ProductResponse>> getProductList(Integer pageNum, Integer pageSize, Long userId) {
        // 获取商家店铺
        Shop shop = getShopByUserId(userId);
        if (shop == null) {
            return Result.error("店铺不存在");
        }

        // 分页查询商品
        Page<Product> page = new Page<>(pageNum, pageSize);
        Page<Product> productPage = productMapper.selectPage(page,
            new LambdaQueryWrapper<Product>()
                .eq(Product::getShopId, shop.getId())
                .orderByDesc(Product::getCreatedAt)
        );

        // 转换为响应对象
        Page<ProductResponse> responsePage = new Page<>();
        BeanUtils.copyProperties(productPage, responsePage, "records");
        
        // 转换商品列表
        List<ProductResponse> productResponses = productPage.getRecords().stream()
            .map(this::convertToProductResponse)
            .collect(Collectors.toList());
        responsePage.setRecords(productResponses);

        return Result.success(responsePage);
    }

    @Override
    public Result<List<CategoryResponse>> getCategories() {
        // 获取所有启用的分类
        List<Category> categories = categoryMapper.selectList(
            new LambdaQueryWrapper<Category>()
                .eq(Category::getStatus, 1)
                .orderByAsc(Category::getSort)
        );

        // 构建分类树
        List<CategoryResponse> tree = buildCategoryTree(categories);
        return Result.success(tree);
    }

    @Override
    @Transactional
    public Result<?> updateStock(Long productId, Integer quantity, String type) {
        // 获取商品
        Product product = productMapper.selectById(productId);
        if (product == null) {
            return Result.error("商品不存在");
        }

        // 记录原库存
        int beforeStock = product.getStock();
        int afterStock;

        // 根据类型更新库存
        switch (type) {
            case "IN":
                afterStock = beforeStock + quantity;
                break;
            case "OUT":
                if (beforeStock < quantity) {
                    return Result.error("库存不足");
                }
                afterStock = beforeStock - quantity;
                break;
            default:
                return Result.error("无效的操作类型");
        }

        // 更新商品库存
        product.setStock(afterStock);
        productMapper.updateById(product);

        // 记录库存变更
        ProductStockLog log = new ProductStockLog();
        log.setProductId(productId);
        log.setChangeType("IN".equals(type) ? 1 : 2);
        log.setChangeQuantity(quantity);
        log.setBeforeStock(beforeStock);
        log.setAfterStock(afterStock);
        stockLogMapper.insert(log);

        return Result.success();
    }

    @Override
    public Result<?> getProductStats(Long productId) {
        // 获取今日统计数据
        LocalDate today = LocalDate.now();
        ProductStats stats = statsMapper.selectOne(
            new LambdaQueryWrapper<ProductStats>()
                .eq(ProductStats::getProductId, productId)
                .eq(ProductStats::getStatsDate, today)
        );

        if (stats == null) {
            stats = new ProductStats();
            stats.setProductId(productId);
            stats.setStatsDate(today);
        }

        return Result.success(stats);
    }

    @Override
    public Result<?> getHotProducts(Integer limit) {
        // 获取热门商品（基于销量）
        List<Product> products = productMapper.selectList(
            new LambdaQueryWrapper<Product>()
                .eq(Product::getStatus, 1)
                .orderByDesc(Product::getSales)
                .last("LIMIT " + limit)
        );

        return Result.success(convertToProductResponse(products));
    }

    @Override
    public Result<?> getNewProducts(Integer limit) {
        // 获取新品（基于创建时间）
        List<Product> products = productMapper.selectList(
            new LambdaQueryWrapper<Product>()
                .eq(Product::getStatus, 1)
                .orderByDesc(Product::getCreatedAt)
                .last("LIMIT " + limit)
        );

        return Result.success(convertToProductResponse(products));
    }

    // 辅助方法
    private Shop getShopByUserId(Long userId) {
        return shopMapper.selectOne(
            new LambdaQueryWrapper<Shop>()
                .eq(Shop::getUserId, userId)
        );
    }

    private Product checkProductOwnership(Long productId, Long userId) {
        Shop shop = getShopByUserId(userId);
        if (shop == null) {
            return null;
        }

        return productMapper.selectOne(
            new LambdaQueryWrapper<Product>()
                .eq(Product::getId, productId)
                .eq(Product::getShopId, shop.getId())
        );
    }

    private void saveProductImages(Long productId, List<Long> imageIds) {
        for (int i = 0; i < imageIds.size(); i++) {
            ProductImage productImage = new ProductImage();
            productImage.setProductId(productId);
            productImage.setImageId(imageIds.get(i));
            productImage.setSort(i);
            productImage.setType(i == 0 ? 1 : 2); // 第一张为主图
            productImageMapper.insert(productImage);
        }
    }

    private void saveProductSpecs(Long productId, List<ProductSpecRequest> specs) {
        for (ProductSpecRequest spec : specs) {
            ProductSpec productSpec = new ProductSpec();
            BeanUtils.copyProperties(spec, productSpec);
            productSpec.setProductId(productId);
            productSpecMapper.insert(productSpec);
        }
    }

    private List<ProductResponse> convertToProductResponse(List<Product> products) {
        return products.stream().map(this::convertToProductResponse).collect(Collectors.toList());
    }

    private ProductResponse convertToProductResponse(Product product) {
        ProductResponse response = new ProductResponse();
        BeanUtils.copyProperties(product, response);

        // 设置店铺信息
        Shop shop = shopMapper.selectById(product.getShopId());
        if (shop != null) {
            ShopResponse shopResponse = new ShopResponse();
            BeanUtils.copyProperties(shop, shopResponse);
            response.setShop(shopResponse);
        }

        // 设置分类信息
        Category category = categoryMapper.selectById(product.getCategoryId());
        if (category != null) {
            CategoryResponse categoryResponse = new CategoryResponse();
            BeanUtils.copyProperties(category, categoryResponse);
            response.setCategory(categoryResponse);
        }

        // 设置商品图片
        List<ProductImage> images = productImageMapper.selectList(
            new LambdaQueryWrapper<ProductImage>()
                .eq(ProductImage::getProductId, product.getId())
                .orderByAsc(ProductImage::getSort)
        );
        response.setImages(images.stream()
            .map(ProductImage::getImageId)
            .map(String::valueOf)
            .collect(Collectors.toList()));

        // 设置商品规格
        List<ProductSpec> specs = productSpecMapper.selectList(
            new LambdaQueryWrapper<ProductSpec>()
                .eq(ProductSpec::getProductId, product.getId())
        );
        response.setSpecs(specs.stream().map(spec -> {
            ProductSpecResponse specResponse = new ProductSpecResponse();
            BeanUtils.copyProperties(spec, specResponse);
            return specResponse;
        }).collect(Collectors.toList()));

        return response;
    }

    private Page<ProductResponse> convertToProductResponsePage(Page<Product> productPage) {
        Page<ProductResponse> responsePage = new Page<>();
        BeanUtils.copyProperties(productPage, responsePage, "records");
        responsePage.setRecords(convertToProductResponse(productPage.getRecords()));
        return responsePage;
    }

    private List<ProductReviewResponse> convertToReviewResponse(List<ProductReview> reviews) {
        return reviews.stream().map(review -> {
            ProductReviewResponse response = new ProductReviewResponse();
            BeanUtils.copyProperties(review, response);

            // 设置用户信息
            User user = userMapper.selectById(review.getUserId());
            if (user != null) {
                response.setUsername(user.getUsername());
                response.setUserAvatar(user.getAvatarUrl());
            }

            return response;
        }).collect(Collectors.toList());
    }

    // 构建分类树的辅助方法
    private List<CategoryResponse> buildCategoryTree(List<Category> categories) {
        // 按父ID分组
        Map<Long, List<Category>> parentMap = categories.stream()
            .collect(Collectors.groupingBy(
                category -> category.getParentId() == null ? 0L : category.getParentId()
            ));

        // 构建一级分类树
        return buildCategoryTreeRecursive(0L, parentMap);
    }

    // 递归构建分类树
    private List<CategoryResponse> buildCategoryTreeRecursive(Long parentId, Map<Long, List<Category>> parentMap) {
        List<Category> children = parentMap.get(parentId);
        if (children == null) {
            return null;
        }

        return children.stream().map(category -> {
            CategoryResponse response = new CategoryResponse();
            BeanUtils.copyProperties(category, response);
            response.setChildren(buildCategoryTreeRecursive(category.getId(), parentMap));
            return response;
        }).collect(Collectors.toList());
    }
}